<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="search_name" clearable placeholder="请输入账号名称" style="width: 200px;margin-right: 20px" class="filter-item" />
      <el-input v-model="search_role" clearable placeholder="请输入角色名称" style="width: 200px;" class="filter-item" />
      <el-button style="margin-left: 20px" class="filter-item" type="primary" icon="el-icon-search" @click="getUserList">
        查询
      </el-button>
      <el-button style="margin-left: 20px" class="filter-item" type="primary" @click="handleAddUser">添加账号</el-button>
    </div>
    <el-table :data="UserList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="账号Id" width="100">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号名称" width="100">
        <template slot-scope="scope">
          {{ scope.row.account }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号简介" width="100">
        <template slot-scope="scope">
          {{ scope.row.info }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号头像" width="100">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.ava_url" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后一次登陆时间" width="220">
        <template slot-scope="scope">
          {{ scope.row.login_time }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="绑定角色" width="220">
        <template slot-scope="scope">
          {{ scope.row.role_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否有效">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
            @change="checkStatus(scope)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑账号':'新增账号'">
      <el-form ref="UserAdd" :model="UserAdd" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="账号名称" prop="account">
          <el-input v-model="UserAdd.account" placeholder="输入账号名称" />
        </el-form-item>
        <el-form-item label="账号简介" prop="info">
          <el-input v-model="UserAdd.info" placeholder="输入账号简介" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :headers="headers_upload"
            action="/api/admin/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ava_url&&dialogType==='edit'" :src="UserAdd.ava_url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="UserAdd.password" show-password placeholder="密码/若不更新密码可不填" />
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword">
          <el-input v-model="UserAdd.repassword" show-password placeholder="确认密码/若不更新密码可不填" />
        </el-form-item>
        <el-form-item label="选择角色" prop="role_id">
          <el-select v-model="UserAdd.role_id" filterable clearable placeholder="请选择角色">
            <el-option
              v-for="item in role_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser">确定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      style="float: right;margin-top: 20px"
      :page-size="limit"
      layout="total, prev, pager, next, jumper"
      :total="total"
      :hide-on-single-page="true"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getUserList, CheckUserStatus, deleteUser, updateUser, addUser, GetRoleList } from '@/api/user'
import { deepClone } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  data() {
    const check_name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'))
      }
    }
    const check_pwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      }
    }
    const check_repwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'))
      }
    }
    const check_role_id = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('需要选择角色～'))
      }
    }
    const check_info = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('需要输入权限简介～'))
      }
    }
    return {
      headers_upload: { 'Token': getToken() },
      total: 0,
      page: 0,
      limit: 0,
      ava_url: 'http://dns.shmilyi.cn/1622683110.jpeg',
      UserAdd: {
        id: undefined,
        account: '',
        password: '',
        repassword: '',
        role_id: undefined,
        ava_url: 'http://dns.shmilyi.cn/1622683110.jpeg',
        info: ''
      },
      UserList: [],
      dialogVisible: false,
      dialogType: 'new',
      search_name: '',
      search_role: '',
      role_list: [],
      rules: {
        account: [
          { validator: check_name, trigger: 'blur' }
        ],
        password: [
          { validator: check_pwd, trigger: 'blur' }
        ],
        repassword: [
          { validator: check_repwd, trigger: 'blur' }
        ],
        role_id: [
          { validator: check_role_id, trigger: 'blur' }
        ],
        info: [
          { validator: check_info, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
  },
  created() {
    this.getUserList()
    this.GetRoleList()
  },
  methods: {
    handleAvatarSuccess(res) {
      this.ava_url = res.data.url
      this.UserAdd.ava_url = res.data.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async getUserList() {
      const res = await getUserList(this.search_name, this.search_role, this.page, this.limit)
      this.UserList = res.data.data
      this.total = res.data.total
      this.limit = parseInt(res.data.per_page)
    },
    async GetRoleList() {
      const res = await GetRoleList()
      this.role_list = res.data
    },
    async handleCurrentChange(e) {
      const res = await getUserList(this.search_name, this.search_role, e, this.limit)
      this.UserList = res.data.data
      this.total = res.data.total
      this.limit = parseInt(res.data.per_page)
    },
    handleAddUser() {
      this.UserAdd = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.UserAdd = deepClone(scope.row)
      this.$nextTick(() => {
      })
    },
    async checkStatus(e) {
      const res = await CheckUserStatus(e.row.status, e.row.id)
      switch (res.code) {
        case -1:
          this.$message({
            type: 'error',
            message: res.msg || 'Error'
          })
          break
        case 200:
          this.$message({
            type: 'success',
            message: res.msg || 'Success'
          })
          break
      }
    },
    handleDelete({ row }) {
      this.$confirm('是否确定要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteUser(row.id)
          switch (res.code) {
            case -1:
              this.$message({
                type: 'error',
                message: res.msg || 'Error'
              })
              break
            case 200:
              this.$message({
                type: 'success',
                message: res.msg || 'Success'
              })
              location.reload()
              break
          }
        })
        .catch()
    },
    async confirmUser() {
      this.$refs.UserAdd.validate((valid) => {
        if (!valid) {
          // return false
        }
      })
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        const hash = require('js-sha256').sha256
        const pwd = this.UserAdd.password
        const repwd = this.UserAdd.repassword
        if (pwd !== undefined && repwd !== undefined) {
          this.UserAdd.password = hash(this.UserAdd.password)
          this.UserAdd.repassword = hash(this.UserAdd.repassword)
        }
        const res = await updateUser(this.UserAdd)
        switch (res.code) {
          case -1:
            this.$message({
              type: 'error',
              message: res.msg || 'Error'
            })
            break
          case 200:
            this.$message({
              type: 'success',
              message: res.msg || 'Success'
            })
            this.dialogVisible = false
            location.reload()
            break
        }
      } else {
        const hash = require('js-sha256').sha256
        const pwd = this.UserAdd.password
        const repwd = this.UserAdd.repassword
        if (pwd !== undefined && repwd !== undefined) {
          this.UserAdd.password = hash(this.UserAdd.password)
          this.UserAdd.repassword = hash(this.UserAdd.repassword)
        }
        const res = await addUser(this.UserAdd)
        switch (res.code) {
          case -1:
            this.$message({
              type: 'error',
              message: res.msg || 'Error'
            })
            break
          case 200:
            this.$message({
              type: 'success',
              message: res.msg || 'Success'
            })
            this.dialogVisible = false
            location.reload()
            break
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
